<template>
  <div class="SvgSliderBox">
    <svg width="100%" height="21">
      <line x1="0" y1="50%" :x2="cx-6.5" y2="50%" stroke-width="2" stroke="#00a5e4" stroke-linecap="round"></line>
      <line :x1="cx+6.5" y1="50%" :x2="boxSize.width" y2="50%" stroke-width="2" stroke="#e0e0e0"
            stroke-linecap="round"/>
      <circle :cx="cx" cy="50%" r="6.5" fill="#00a5e4"
              @mousedown="handleCircleMousedown"
              @touchstart="handleCircleMousedown"/>
    </svg>
    <vue-resize-sensor initial @resize="handleResize"/>
  </div>
</template>

<script>
  import vueResizeSensor from 'vue-resize-sensor'
  import {openMask} from "@/components/Marking/util/util";

  export default {
    components: {vueResizeSensor},
    name: "Slider",
    props: {
      value: {
        type: Number,
        default: 0.5
      },
      min: {
        type: Number,
        default: 0
      },
      max: {
        type: Number,
        default: 1
      },
      step: {
        type: Number,
        default: 1
      }
    },
    data() {
      return {
        tempValue: 0,
        boxSize: {width: 0, height: 0}
      }
    },
    computed: {
      r() {
        return (this.privateValue - this.min) / (this.max - this.min)
      },
      privateValue: {
        get() {
          return this.tempValue
        },
        set(val) {
          if (val < this.min) val = this.min
          if (val > this.max) val = this.max
          val = Number(val.toFixed(`${this.step}`.replace(/\d+\.?/, '').length))
          this.tempValue = val
          this.$emit('input', val)
        }
      },
      cx() {
        return (this.boxSize.width - 13) * this.r + 6.5
      }
    },
    mounted() {
      this.privateValue = this.value
    },
    watch: {
      value() {
        this.privateValue = this.value
      }
    },
    methods: {
      handleResize(size) {
        this.boxSize = size
      },
      handleCircleMousedown(e) {
        e.preventDefault()
        e.changedTouches && (e = e.changedTouches[0])
        let startPageX = e.pageX
        let startCx = this.cx
        let move = e => {
          let deltaPagex = e.pageX - startPageX
          this.privateValue = (startCx + deltaPagex - 6.5) / (this.boxSize.width - 13) * (this.max - this.min) + this.min
        }
        openMask(move)
      }
    }
  }
</script>

<style scoped lang="scss">
  .SvgSliderBox {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 21px;
  }
</style>
